<template>
  <div class="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-50">
    <div class="container mx-auto px-4 py-8">
      <!-- 页面标题 -->
      <div class="mb-8 text-center">
        <div class="inline-flex items-center justify-center w-16 h-16 bg-gradient-to-r from-blue-600 to-purple-600 rounded-2xl mb-4 shadow-lg">
          <svg class="w-8 h-8 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"></path>
          </svg>
        </div>
        <h1 class="text-4xl font-bold bg-gradient-to-r from-gray-900 to-gray-700 bg-clip-text text-transparent mb-2">项目广场</h1>
        <p class="text-gray-600 text-lg">发现优秀的开源项目和创意作品</p>
      </div>

      <!-- 搜索和筛选 -->
      <div class="bg-white/80 backdrop-blur-sm rounded-2xl shadow-lg border border-white/20 p-6 mb-8">
        <div class="flex flex-col lg:flex-row gap-4">
          <!-- 搜索框 -->
          <div class="flex-1">
            <div class="relative">
              <input
                v-model="searchQuery"
                @input="handleSearch"
                type="text"
                placeholder="搜索项目..."
                class="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200"
              >
              <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                <svg class="h-5 w-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
                </svg>
              </div>
            </div>
          </div>

          <!-- 筛选器 -->
          <div class="flex flex-wrap gap-3">
            <select
              v-model="filters.type"
              @change="handleFilter"
              class="px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200"
            >
              <option value="">所有类型</option>
              <option value="web">Web应用</option>
              <option value="mobile">移动应用</option>
              <option value="desktop">桌面应用</option>
              <option value="library">开源库</option>
              <option value="tool">开发工具</option>
            </select>

            <select
              v-model="filters.difficulty"
              @change="handleFilter"
              class="px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200"
            >
              <option value="">所有难度</option>
              <option value="beginner">入门</option>
              <option value="intermediate">中级</option>
              <option value="advanced">高级</option>
            </select>

            <select
              v-model="filters.sort"
              @change="handleFilter"
              class="px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200"
            >
              <option value="latest">最新</option>
              <option value="popular">最受欢迎</option>
              <option value="trending">热门</option>
              <option value="likes">点赞数</option>
            </select>
          </div>
        </div>
      </div>

      <!-- 项目列表 -->
      <div v-if="loading" class="flex justify-center items-center py-12">
        <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500"></div>
        <span class="ml-3 text-gray-600">加载中...</span>
      </div>

      <div v-else-if="error" class="text-center py-12 text-red-500">
        {{ error }}
      </div>

      <div v-else>
        <!-- 项目统计 -->
        <div class="mb-6 text-center">
          <p class="text-gray-600">
            共找到 <span class="font-semibold text-blue-600">{{ totalProjects }}</span> 个项目
          </p>
        </div>

        <!-- 项目网格 -->
        <div v-if="projects.length === 0" class="text-center py-12 text-gray-500">
          <svg class="mx-auto h-12 w-12 text-gray-400 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"></path>
          </svg>
          <p>暂无项目，快来创建第一个项目吧！</p>
        </div>

        <div v-else class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          <div
            v-for="project in projects"
            :key="project.id"
            class="bg-white/80 backdrop-blur-sm rounded-2xl shadow-lg hover:shadow-xl transition-all duration-300 transform hover:scale-105 border border-white/20 overflow-hidden"
          >
            <!-- 项目封面 -->
            <div class="relative h-48 bg-gradient-to-br from-blue-100 to-purple-100">
              <img
                v-if="project.cover_image"
                :src="project.cover_image"
                :alt="project.title"
                class="w-full h-full object-cover"
              >
              <div v-else class="w-full h-full flex items-center justify-center">
                <svg class="w-16 h-16 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"></path>
                </svg>
              </div>
              
              <!-- 项目状态标签 -->
              <div class="absolute top-3 left-3">
                <span
                  :class="[
                    'px-2 py-1 rounded-full text-xs font-semibold',
                    {
                      'bg-green-100 text-green-800': project.status === 'approved',
                      'bg-yellow-100 text-yellow-800': project.status === 'pending',
                      'bg-red-100 text-red-800': project.status === 'rejected'
                    }
                  ]"
                >
                  {{ project.status === 'approved' ? '已发布' : project.status === 'pending' ? '审核中' : '已拒绝' }}
                </span>
              </div>

              <!-- 难度标签 -->
              <div class="absolute top-3 right-3">
                <span
                  :class="[
                    'px-2 py-1 rounded-full text-xs font-semibold',
                    {
                      'bg-green-100 text-green-800': project.difficulty === 'beginner',
                      'bg-yellow-100 text-yellow-800': project.difficulty === 'intermediate',
                      'bg-red-100 text-red-800': project.difficulty === 'advanced'
                    }
                  ]"
                >
                  {{ project.difficulty === 'beginner' ? '入门' : project.difficulty === 'intermediate' ? '中级' : '高级' }}
                </span>
              </div>
            </div>

            <!-- 项目信息 -->
            <div class="p-6">
              <h3 class="text-xl font-bold text-gray-900 mb-2 line-clamp-1">{{ project.title }}</h3>
              <p class="text-gray-600 text-sm mb-4 line-clamp-2">{{ project.description }}</p>

              <!-- 技术栈 -->
              <div class="flex flex-wrap gap-2 mb-4">
                <span
                  v-for="tech in project.tech_stack.slice(0, 3)"
                  :key="tech"
                  class="px-2 py-1 bg-blue-100 text-blue-800 text-xs rounded-full"
                >
                  {{ tech }}
                </span>
                <span
                  v-if="project.tech_stack.length > 3"
                  class="px-2 py-1 bg-gray-100 text-gray-600 text-xs rounded-full"
                >
                  +{{ project.tech_stack.length - 3 }}
                </span>
              </div>

              <!-- 统计信息 -->
              <div class="flex items-center justify-between text-sm text-gray-500 mb-4">
                <div class="flex items-center space-x-4">
                  <span class="flex items-center">
                    <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"></path>
                    </svg>
                    {{ project.like_count }}
                  </span>
                  <span class="flex items-center">
                    <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>
                    </svg>
                    {{ project.view_count }}
                  </span>
                </div>
                <span>{{ formatTime(project.created_at) }}</span>
              </div>

              <!-- 作者信息 -->
              <div class="flex items-center justify-between">
                <div class="flex items-center">
                  <img
                    :src="project.author.avatar_url || '/static/avatar/default.jpg'"
                    :alt="project.author.username"
                    class="w-8 h-8 rounded-full mr-3"
                  >
                  <div>
                    <p class="text-sm font-medium text-gray-900">{{ project.author.username }}</p>
                    <p class="text-xs text-gray-500">{{ project.type }}</p>
                  </div>
                </div>
                <button
                  @click="viewProject(project.id)"
                  class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors text-sm"
                >
                  查看详情
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div v-if="totalPages > 1" class="mt-8 flex justify-center">
          <nav class="flex items-center space-x-2">
            <button
              @click="goToPage(currentPage - 1)"
              :disabled="currentPage === 1"
              class="px-3 py-2 rounded-lg border border-gray-300 text-gray-500 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              上一页
            </button>
            
            <button
              v-for="page in visiblePages"
              :key="page"
              @click="goToPage(page)"
              :class="[
                'px-3 py-2 rounded-lg border transition-colors',
                page === currentPage
                  ? 'bg-blue-500 text-white border-blue-500'
                  : 'border-gray-300 text-gray-700 hover:bg-gray-50'
              ]"
            >
              {{ page }}
            </button>
            
            <button
              @click="goToPage(currentPage + 1)"
              :disabled="currentPage === totalPages"
              class="px-3 py-2 rounded-lg border border-gray-300 text-gray-500 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              下一页
            </button>
          </nav>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { projectApi } from '@/api/project'

// 简单的防抖函数
const debounce = (func: Function, delay: number) => {
  let timeoutId: number
  return (...args: any[]) => {
    clearTimeout(timeoutId)
    timeoutId = setTimeout(() => func.apply(null, args), delay)
  }
}

const router = useRouter()

// 响应式数据
const projects = ref<any[]>([])
const loading = ref(false)
const error = ref('')
const totalProjects = ref(0)
const currentPage = ref(1)
const pageSize = ref(12)

// 搜索和筛选
const searchQuery = ref('')
const filters = ref({
  type: '',
  difficulty: '',
  sort: 'latest'
})

// 计算属性
const totalPages = computed(() => Math.ceil(totalProjects.value / pageSize.value))

const visiblePages = computed(() => {
  const pages = []
  const start = Math.max(1, currentPage.value - 2)
  const end = Math.min(totalPages.value, currentPage.value + 2)
  
  for (let i = start; i <= end; i++) {
    pages.push(i)
  }
  return pages
})

// 方法
const loadProjects = async () => {
  loading.value = true
  error.value = ''
  
  try {
    const response = await projectApi.getProjects({
      page: currentPage.value,
      page_size: pageSize.value,
      search: searchQuery.value,
      type: filters.value.type,
      difficulty: filters.value.difficulty,
      sort: filters.value.sort
    })
    
    if (response.data) {
      projects.value = response.data.items
      totalProjects.value = response.data.total
    }
  } catch (err) {
    console.error('加载项目列表失败:', err)
    error.value = '加载项目列表失败，请稍后重试'
  } finally {
    loading.value = false
  }
}

const handleSearch = debounce(() => {
  currentPage.value = 1
  loadProjects()
}, 500)

const handleFilter = () => {
  currentPage.value = 1
  loadProjects()
}

const goToPage = (page: number) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
    loadProjects()
  }
}

const viewProject = (projectId: number) => {
  router.push(`/projects/${projectId}`)
}

const formatTime = (dateString: string) => {
  const date = new Date(dateString)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  
  if (diff < 1000 * 60) {
    return '刚刚'
  } else if (diff < 1000 * 60 * 60) {
    return `${Math.floor(diff / (1000 * 60))}分钟前`
  } else if (diff < 1000 * 60 * 60 * 24) {
    return `${Math.floor(diff / (1000 * 60 * 60))}小时前`
  } else {
    return `${Math.floor(diff / (1000 * 60 * 60 * 24))}天前`
  }
}

onMounted(() => {
  loadProjects()
})
</script>

<style scoped>
.line-clamp-1 {
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style>
